package delivery.order.service.api;

import delivery.order.service.constant.PathConstant;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.File;

@RestController
public class MAIN_000_000_001 {
    private static final Logger logger = LoggerFactory.getLogger(MAIN_000_000_001.class);

    //预览PDF
    @CrossOrigin(origins = "*") // 允许所有源
    @GetMapping(value = "/preview/{pdfName}")
    @ResponseBody
    public ResponseEntity<Resource> doPost(@PathVariable String pdfName) {
        try {
            // 参数校验
            if (pdfName == null || pdfName.trim().isEmpty()) {
                return ResponseEntity.badRequest().build();//请求的文件名为空
            }
            // 路径遍历攻击防护 - 规范化并验证文件名
            String safeFileName = sanitizeFileName(pdfName);
            if (safeFileName == null) {
                return ResponseEntity.badRequest().build();//潜在路径遍历攻击检测
            }
            // 判断文件是否存在
            String filePath = PathConstant.getOutputFolderPath() + "/" + safeFileName;
            File file = new File(filePath);
            if (!file.exists()) {
                return ResponseEntity.notFound().build();
            }
            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=" + safeFileName);
            headers.setContentType(MediaType.APPLICATION_PDF);
            // 返回文件内容
            Resource resource = new FileSystemResource(file);
            return ResponseEntity.ok().headers(headers).contentLength(file.length()).body(resource);
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }

    // 辅助方法：文件名消毒和验证
    private String sanitizeFileName(String fileName) {
        if (fileName == null) {
            return null;
        }
        // 移除路径遍历序列
        String cleanName = fileName.replaceAll("\\.\\./|\\.\\.\\\\", "");
        // 移除可能有害的字符
        cleanName = cleanName.replaceAll("[\\\\/:*?\"<>|]", "");
        // 检查是否为空或只包含空白字符
        if (cleanName.trim().isEmpty()) {
            return null;
        }
        return cleanName;
    }

}
